import React from 'react'
import { Switch, Route, Redirect } from 'react-router-dom';
import Home from './pages/Home';
import List from './pages/List';
import Detail from './pages/Detail';
import Cart from './pages/Cart';
import My from './pages/My';
import AdB from './pages/AdB';
import Login from './pages/Login';

// 需要授权才能看到的页面列表 ，如果用户已登录则按照Route渲染
let authList = [{ path: '/my', component: My }, { path: '/cart', component: Cart }];


// 存放需要跳转登录的
let needLoginList = [];


// 判断如果token不存在，就把需要授权的页面列表全部移入登录跳转 ，且清空authList列表
if (!window.localStorage.getItem('token')) {
  needLoginList = [...authList];
  authList = [];
}


export default function App() {

  return (

    <div>
      <Switch>
        <Route path="/home" component={Home}></Route>
        <Route path="/list" component={List}></Route>
        <Route path="/detail/:id" component={Detail}></Route>
        <Route path="/login" component={Login}></Route>
        {/**需要登录的都重定向**/}
        {needLoginList.map((v, i) => {
          return <Redirect key={i} from={v.path} to="/login"></Redirect>
        })}

        {/**用户已经登录的这里直接渲染route**/}
        {authList.map((v, i) => {
          return <Route path={v.path} component={v.component}></Route>
        })}

        <Route path="/adb" component={AdB}></Route>
        <Redirect from="/ada" to="/adb"></Redirect>
        <Redirect from="/" to="/home"></Redirect>
      </Switch>


    </div>
  )
}
